package andy.demo.parseXML.dom.service;



import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import andy.demo.parseXML.sax.domain.Person;



public class DOMService {
//	
//	private Person person;
//	private ArrayList<Person> personList;
	

	public static ArrayList<Person>  readXML(InputStream in) {
		
		ArrayList<Person> personList = new ArrayList<Person>();
		
		DocumentBuilderFactory factory=null;
        DocumentBuilder builder=null;
        Document document=null;
        InputStream inputStream=null;
        
        
        try {
        	//首先找到xml文件
            factory=DocumentBuilderFactory.newInstance();
			builder = factory.newDocumentBuilder();
			document = builder.parse(in);
			
			//找到根Element
            Element root=document.getDocumentElement();
            //由根节点取到所有的peson节点，并放置在nodes中
            NodeList nodes=root.getElementsByTagName("person");
           //遍历根节点所有子节点,persons 下所有person
            for(int i=0; i<nodes.getLength(); i++) {
            	
            	Person person = new Person();
            	//取出第i个person标签
            	Element personElement = (Element) nodes.item(i);
            	//取出person中的Id属性
            	person.setId( Integer.parseInt(personElement.getAttribute("id")) );
            	//通过person标签，取出第0个name标签  ---item(0)--- 这说明person标签下面还可以有N个name标签
            	Element nameElement = (Element) personElement.getElementsByTagName("name").item(0);
            	person.setPersonName(nameElement.getFirstChild().getNodeValue());
            	
            	Element ageElement = (Element) personElement.getElementsByTagName("age").item(0);
            	person.setAge(ageElement.getFirstChild().getNodeValue());
            	
            	
            	personList.add(person);
            	
            }
            
			
			
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return personList;
	}
}
